from datetime import datetime

import requests
import time
import matplotlib.pyplot as plt
import numpy as np
import hmac
import hashlib
import base64
import requests
import json
import urllib.parse

from jinja2 import Template

prometheus_url = "http://x.x.x.x:9090/api/v1/query"
# 获取当前时间的时间戳（秒级）
current_time_seconds = int(time.time())
# 获取系统当前时间的小数部分并乘以1000，得到毫秒数
milliseconds = int((time.time() % 1) * 1000)
# 组合成 Time 的形式的字符串
time_combined = f"{current_time_seconds}.{milliseconds}"
ip_addresses = {
    "node-10.106.8.30",
    "node-10.106.8.31",
    "node-10.106.8.32",
    "node-10.106.8.33",
    "node-10.106.8.34",
    "node-10.106.8.35",
    "node-10.106.8.36",
    "node-10.106.8.37",
    "node-10.144.10.40",
    "node-10.144.10.41",
    "node-10.144.10.42",
}
dns_ip = {
    "node-10.110.2.104",
    "node-10.110.2.103",
    "node-10.144.99.31",
    "node-10.144.99.32",
    "node-10.110.2.101",
    "node-10.110.2.102",
    "node-10.144.99.33",
}
#初始化字典来存储数据
data = {}

# 循环查询每个IP地址的CPU、内存和磁盘容量
#jms主机
for ip in ip_addresses:
    data[ip] = {'cpu': None, 'mem': None, 'storage': {}}
    # CPU使用率查询
    cpu_query = f'(100 - (avg by(job,instance,role) (irate(node_cpu_seconds_total{{job =~ "cloud-other-linux-consul",instance=~"{ip}",mode="idle"}}[5m])) * 100))'
    cpu_full_url = f"{prometheus_url}?query={cpu_query}&time={time_combined}"
    cpu_response = requests.get(cpu_full_url)
    cpu_data = cpu_response.json()
    # print(cpu_data)
    # 提取role对应的值存储到data里
    for result in cpu_data['data']['result']:
        cpu_role = result['metric']['role']
        cpu_value = result['value'][1]
        cpu_rounded_value = f"{round(float(cpu_value), 2)}%"
        data[ip]['cpu'] = f"{cpu_rounded_value}"

    # 内存使用率查询
    mem_query = f'((node_memory_MemTotal_bytes{{job =~ "cloud-other-linux-consul",instance=~"{ip}"}} - node_memory_MemAvailable_bytes{{job =~ "cloud-other-linux-consul",instance=~"{ip}"}}) / node_memory_MemTotal_bytes{{job =~ "cloud-other-linux-consul",instance=~"{ip}"}})*100'
    mem_full_url = f"{prometheus_url}?query={mem_query}&time={time_combined}"
    mem_response = requests.get(mem_full_url)
    mem_data = mem_response.json()
    # 提取role对应的值存储到data里
    for result in mem_data['data']['result']:
        mem_role = result['metric']['role']
        mem_value = result['value'][1]
        men_rounded_value = f"{round(float(mem_value), 2)}%"
        data[ip]['mem'] = f"{men_rounded_value}"
        # print("内存",mem_role, men_rounded_value)

    # 磁盘使用率查询
    storage_query = f'100 - ((node_filesystem_avail_bytes{{fstype=~"ext4|xfs|nfs|nfs4", job =~ "cloud-other-linux-consul",instance=~"{ip}"}} * 100) / node_filesystem_size_bytes {{fstype=~"ext4|xfs|nfs|nfs4", job =~ "cloud-other-linux-consul",instance=~"{ip}"}})'
    storage_full_url = f"{prometheus_url}?query={storage_query}&time={time_combined}"
    storage_response = requests.get(storage_full_url)
    storage_data = storage_response.json()
    # 提取mountpoint对应的值存储到data里
    for result in storage_data['data']['result']:
        mountpoint = result['metric']['mountpoint']
        mount_value = result['value'][1]
        mount_rounded_value = f"{round(float(mount_value), 2)}%"
        data[ip]['storage'][mountpoint] = f"{mount_rounded_value}"
print(data)

#dns主机
dns_data = {}
for ip in dns_ip:
    dns_data[ip] = {'cpu': None, 'mem': None, 'storage': {}}
    # CPU使用率查询
    cpu_query = f'(100 - (avg by(job,instance,role) (irate(node_cpu_seconds_total{{job =~ "cloud-other-linux-consul",instance=~"{ip}",mode="idle"}}[5m])) * 100))'
    cpu_full_url = f"{prometheus_url}?query={cpu_query}&time={time_combined}"
    cpu_response = requests.get(cpu_full_url)
    cpu_data = cpu_response.json()
    # print(cpu_data)
    # 提取role对应的值存储到data里
    for result in cpu_data['data']['result']:
        cpu_role = result['metric']['role']
        cpu_value = result['value'][1]
        cpu_rounded_value = f"{round(float(cpu_value), 2)}%"
        dns_data[ip]['cpu'] = f"{cpu_rounded_value}"

    # 内存使用率查询
    mem_query = f'((node_memory_MemTotal_bytes{{job =~ "cloud-other-linux-consul",instance=~"{ip}"}} - node_memory_MemAvailable_bytes{{job =~ "cloud-other-linux-consul",instance=~"{ip}"}}) / node_memory_MemTotal_bytes{{job =~ "cloud-other-linux-consul",instance=~"{ip}"}})*100'
    mem_full_url = f"{prometheus_url}?query={mem_query}&time={time_combined}"
    mem_response = requests.get(mem_full_url)
    mem_data = mem_response.json()
    # 提取role对应的值存储到data里
    for result in mem_data['data']['result']:
        mem_role = result['metric']['role']
        mem_value = result['value'][1]
        men_rounded_value = f"{round(float(mem_value), 2)}%"
        dns_data[ip]['mem'] = f"{men_rounded_value}"
        # print("内存",mem_role, men_rounded_value)

    # 磁盘使用率查询
    storage_query = f'100 - ((node_filesystem_avail_bytes{{fstype=~"ext4|xfs|nfs|nfs4", job =~ "cloud-other-linux-consul",instance=~"{ip}"}} * 100) / node_filesystem_size_bytes {{fstype=~"ext4|xfs|nfs|nfs4", job =~ "cloud-other-linux-consul",instance=~"{ip}"}})'
    storage_full_url = f"{prometheus_url}?query={storage_query}&time={time_combined}"
    storage_response = requests.get(storage_full_url)
    storage_data = storage_response.json()
    # 提取mountpoint对应的值存储到data里
    for result in storage_data['data']['result']:
        mountpoint = result['metric']['mountpoint']
        mount_value = result['value'][1]
        mount_rounded_value = f"{round(float(mount_value), 2)}%"
        dns_data[ip]['storage'][mountpoint] = f"{mount_rounded_value}"
print(dns_data)

# '''
# #windows主机
# win_data = {}
# for win_ip in windows_ip:
#     win_data[win_ip] = {'cpu': None, 'mem': None, 'storage': {}}
#     # CPU使用率查询
#     cpu_query = f'(100 - (avg by(instance, role,app) (irate(windows_cpu_time_total{{job=~"cloud-other-windows-consul",instance=~"{win_ip}",  mode="idle"}}[5m])) * 100))'
#     cpu_full_url = f"{prometheus_url}?query={cpu_query}&time={time_combined}"
#     cpu_response = requests.get(cpu_full_url)
#     cpu_data = cpu_response.json()
#     # 提取role对应的值
#     for result in cpu_data['data']['result']:
#         cpu_role = result['metric']['role']
#         cpu_value = result['value'][1]
#         cpu_rounded_value = f"{round(float(cpu_value), 2)}%"
#         win_data[win_ip]['cpu'] = f"{cpu_rounded_value}"
#
#     # 内存使用率查询
#     mem_query = f'100 - (windows_os_physical_memory_free_bytes{{job=~"cloud-other-windows-consul",instance=~"{win_ip}"}} / windows_cs_physical_memory_bytes{{job=~"cloud-other-windows-consul",instance=~"{win_ip}"}})*100'
#     mem_full_url = f"{prometheus_url}?query={mem_query}&time={time_combined}"
#     mem_response = requests.get(mem_full_url)
#     mem_data = mem_response.json()
#     # 提取role对应的值
#     for result in mem_data['data']['result']:
#         mem_role = result['metric']['role']
#         mem_value = result['value'][1]
#         men_rounded_value = f"{round(float(mem_value), 2)}%"
#         win_data[win_ip]['mem'] = f"{men_rounded_value}"
#
#     # 磁盘使用率查询
#     storage_query = f'100 - (windows_logical_disk_free_bytes{{job=~"cloud-other-windows-consul", instance="{win_ip}", volume!~"HarddiskVolume1|HarddiskVolume3" }} / windows_logical_disk_size_bytes{{job=~"cloud-other-windows-consul", instance="{win_ip}", volume!~"HarddiskVolume1|HarddiskVolume3"}})*100'
#     storage_full_url = f"{prometheus_url}?query={storage_query}&time={time_combined}"
#     storage_response = requests.get(storage_full_url)
#     storage_data = storage_response.json()
#     # 提取mountpoint对应的值
#     for result in storage_data['data']['result']:
#         volume = result['metric']['volume']
#         mount_value = result['value'][1]
#         mount_rounded_value = f"{round(float(mount_value), 2)}%"
#         win_data[win_ip]['storage'][volume] = f"{mount_rounded_value}"
# print(win_data)
# '''
# 读取 HTML 模板文件
with open("jms_template.html", "r", encoding="utf-8") as f:
    template_str = f.read()

# 使用 Jinja2 模板引擎渲染 HTML
template = Template(template_str)
rendered_html = template.render(data=data,dns_data=dns_data)
# 生成当前日期时间的字符串，作为文件名的一部分
timestamp = datetime.now().strftime("%Y%m%d-%H%M")
output_html_filename = f"dns-jumpserver_{timestamp}.html"

# 将渲染后的 HTML 写入文件
with open(output_html_filename, "w", encoding="utf-8") as f:
    f.write(rendered_html)


#---------------------推送到钉钉群---------------------------------
def send_to_dingtalk(webhook, secret, link_url):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(hmac_code).decode('utf-8')

    headers = {'Content-Type': 'application/json'}
    url = '{}&timestamp={}&sign={}'.format(webhook, timestamp, sign)

    # 发送链接消息
    link_data = {
        "msgtype": "link",
        "link": {
            "title": title,
            "text": "dns/jumpserver资源巡检点击查看详情",
            "messageUrl": link_url
        }
    }

    response = requests.post(url=url, headers=headers, data=json.dumps(link_data))
    if response.status_code != 200:
        print("Failed to send message to DingTalk group.")
    else:
        print("Message sent to DingTalk group successfully.")


# 填入你的钉钉机器人的Webhook地址和加签密钥
#webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=a3339c727a445ee24fa076f03c3e1819674f972d5047bc42144b2e82b35c35bf'
#正式的webhook
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=94d7c12a420206291f346e2a98fec371ead181e3cc844d97b592af0d3116aafb'
link_url = f'http://x.x.x.x:9998/{output_html_filename}'  # 根据你的实际路径更新
current_date = time.strftime("%Y-%m-%d", time.localtime())
title = 'dns/jumpserver资源巡检-' + current_date
#正式的secret
secret = 'SEC05f7762749bba9cacc1c1f73eab584c57b102b87765cddd2817e0f9cd1640299'
#ceshi
#secret = 'SEC84cd0213e8b88524e48b1c039cf502507f39ea06fd91515fef22f56d0421a073'
# 调用发送链接和图片到钉钉的函数
send_to_dingtalk(webhook_url, secret, link_url)

